<?php

class Round {
	
	public $id;
	public $liga;
	public $datum;

	public $mecevi;
	
		
	// constructor
	
	public function __construct($i = 0) {
		$this->id = $i;
		if ($i != 0) {
			$n = $this->getfromdb($i);
			$this->liga = $n['liga'];
			$this->datum = date("d.m.Y.", strtotime($n['datum']));
		}
	}
	
	// functions
	
	private function getfromdb($number) {
		$q = "SELECT liga, datum FROM kolo WHERE id = " . $number;
		$r = mysql_query("set names 'utf8'");
		$r = mysql_query($q);
		if (!mysql_num_rows($r)) throw new Exception("Ne postoji kolo za zadati ID!");
		return (mysql_fetch_array($r));
	}
		
	public function getMecevi() {
		$q = "SELECT id FROM utakmica WHERE kolo = " . $this->id;
		$r = mysql_query("set names 'utf8'");
		$r = mysql_query($q);
		if (mysql_num_rows($r)) {
			while ($n = mysql_fetch_array($r)) {
				$this->mecevi[] = new Match($n['id']);
			}
		}
	}
	
	public function getFormattedDate($format) {
		return date($format, strtotime($this->datum));
	}
	
	public function findMVP() {
		$mvp = NULL;
		$bli = 0;
		if (count($this->mecevi)) {
		$brOd = 0;
			foreach ($this->mecevi as $mec) {
				$brOd += $mec->odigrana;
			}
			if ($brOd) {
			foreach($this->mecevi as $mec) {
				if ($mec->odigrana) {
					if ($mec->findMVP()->stats[$mec->id]->BLindex > $bli) {
						$bli = $mec->findMVP()->stats[$mec->id]->BLindex;
						$mvp = $mec->findMVP();
						$mvp->stats = $mvp->stats[$mec->id];	// generating mvp stats
					}
				}
			}
			}
		}
		return $mvp;
	}
	
	public function lockFantasy() { //pomocna funkcija za fantasy, proverava kada pocinje kolo
		$trenutni_datum = strtotime('NOW');
		$pom_m_time = strtotime($this->datum);
		$trenutno_time = strtotime(date("H:i", strtotime('NOW')));
		
		var_dump($pom_m_time - $trenutno_time);
		
		if ($trenutni_datum < strtotime($this->datum)){
			return 0;
		}
		elseif($trenutni_datum == strtotime($pom_kolo->datum)){
			if ($pom_m_time - $trenutno_time > 3600){
				return 0;
			}
			else {
				return 1;
			}
		}
		else{
			return 1; // za veliki if
		}
	}


	// admin
	
	public function insertIntoDb() {
		$q = "INSERT INTO kolo (liga, datum) VALUES ('".$this->liga."', '".$this->datum."')";
		$r = mysql_query("set names 'utf8'");
		if (mysql_query($q)) {
			echo "Novo kolo je dodato u bazu podataka";
		}
		
		foreach ($this->mecevi as $mec) {
			$mec->insertIntoDb();
		}
	}
			
} // end of class Round


?>